from spire.xls import *
from spire.xls.common import *
from openpyxl import load_workbook
from openpyxl_image_loader import SheetImageLoader
from openpyxl.drawing.image import Image

def get_image_info_spire(filename):
    workbook = Workbook()
    workbook.LoadFromFile(filename)
    worksheet = workbook.Worksheets[0]

    for i in range(worksheet.Pictures.Count - 1, -1, -1):
        pic = worksheet.Pictures[i]
        print(f"Image found at cell {pic.TopRow}{pic.LeftColumn}")

        pic.Picture.Save(f"D:\\temp\\images\\image_{pic.TopRow}_{pic.LeftColumn}.png")

    workbook.Dispose()
 

# def insert_image_spire(filename):
#     workbook = Workbook()
#     workbook.LoadFromFile(filename)
#     worksheet = workbook.Worksheets[0]

#     # 插入图片
#     picture = worksheet.Pictures.Add(3, 1, "C:\\Users\\高岩\Downloads\\su7_1.jpg")
    
#     # 在指定单元格中插入图片（此处为第一行第二列，即B1单元格）
     

#     # 设置图片宽高度
#     picture.Width = 120
#     picture.Height = 120

#     # 调整图片所在位置的列宽和行高
#     worksheet.Columns[1].ColumnWidth = 20
#     worksheet.Rows[0].RowHeight = 110

#     # 设置单元格边框与图片之间的距离
#     picture.LeftColumnOffset = 90
#     picture.TopRowOffset = 20

#     # 保存文件

#     workbook.SaveToFile("d:\\temp\\ms11-1.xlsx")
#     workbook.Dispose()

def remove_image_spire(filename):
    workbook = Workbook()
    workbook.LoadFromFile(filename)
    worksheet = workbook.Worksheets[0]

    # 删除图片
    for i in range(worksheet.Pictures.Count - 1, -1, -1):
        pic = worksheet.Pictures[i]
        worksheet.Pictures.Remove(pic)

    # 保存文件
    workbook.SaveToFile("删除图片.xlsx", ExcelVersion.Version2016)

    workbook.Dispose()

def replace_image_spire(filename):
    workbook = Workbook()
    workbook.LoadFromFile(filename)
    worksheet = workbook.Worksheets[0]

    # 替换图片
    pic = worksheet.Pictures[0]
    pic.Picture.Save("d:\\temp\\images\\image_1_1.png")
    pic.Picture.LoadImage("d:\\temp\\images\\image_1_1.png")

    # 保存文件
    workbook.SaveToFile("替换图片.xlsx", ExcelVersion.Version2016)

    workbook.Dispose()


def get_image_info_pyxl(filename):
 
    workbook = load_workbook(filename)
    worksheet = workbook.active
    image_loader = SheetImageLoader(worksheet)
    # 遍历工作表中的所有单元格
    for row in worksheet.iter_rows():
        for cell in row:
            # 检查单元格中是否有图片
            if image_loader.image_in(cell.coordinate):
                # 获取图片并保存到本地
                image = image_loader.get(cell.coordinate)
                image.save(f"D:\\temp\\images\\image_{cell.row}_{cell.column}.png")
 
def insert_image_pyxl(filename):
    workbook = load_workbook(filename)
    worksheet = workbook.active
    # 插入图片
    img = Image(r"C:\Users\高岩\Downloads\su7_1.jpg")
    img.height = 120
    img.width = 120
    worksheet.add_image(img, "B5")
    # 保存文件
    workbook.save(r"d:\temp\插入图片1.xlsx")

# get_image_info_spire("d:\\temp\\ms11.xlsx")
# insert_image_spire("d:\\temp\\ms11.xlsx") 收费的 不要用
insert_image_pyxl(r"d:\temp\ms11.xlsx")